package com.cn.demo.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.List;

/**
 * service基类，实现单表的增删改查
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/11/18 14:14
 * @projectName test
 */
public class BaseService<M extends BaseMapper<T>, T> {

    @Autowired
    protected M baseMapper;


    /**
     * 保存
     *
     * @param entity
     * @return int
     * @author: wangjf
     * @createTime: 2019/11/18 14:20
     */
    public int save(T entity) {
        return this.baseMapper.insert(entity);
    }

    /**
     * 根据ID进行更新
     *
     * @param entity
     * @return int
     * @author: wangjf
     * @createTime: 2019/11/18 14:21
     */
    public int updateById(T entity) {
        return this.baseMapper.updateById(entity);

    }

    /**
     * 根据ID进行获取
     *
     * @param id
     * @return T
     * @author: wangjf
     * @createTime: 2019/11/18 14:23
     */
    public T getById(Serializable id) {
        return this.baseMapper.selectById(id);

    }

    /**
     * 根据ID进行删除
     *
     * @param id
     * @return int
     * @author: wangjf
     * @createTime: 2019/11/18 14:24
     */
    public int deleteById(Serializable id) {
        return this.baseMapper.deleteById(id);
    }

    /**
     * 查询列表
     *
     * @param queryWrapper
     * @return java.util.List<T>
     * @author: wangjf
     * @createTime: 2019/11/18 14:26
     */
    public List<T> select(Wrapper<T> queryWrapper) {
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询全部
     * @author: wangjf
     * @createTime: 2019/11/18 14:49
     * @param
     * @return java.util.List<T>
     */
    public List<T> getAll(){
        return this.baseMapper.selectList(Wrappers.query());
    }

    /**
     * 获取一个T
     * @author: wangjf
     * @createTime: 2019/11/20 11:25
     * @param queryWrapper
     * @return T
     */
    public T getOne(Wrapper<T> queryWrapper){
        List<T> list = this.baseMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }


}
